package com.ng.common.util;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

/**
 * SqlInjectionUtil 是一个工具类，用于检测 SQL 注入风险。
 */
@UtilityClass
@Slf4j
public class SqlInjectionUtil {
	// SQL 注入检测的正则表达式数组
	private static final String[] SQL_INJECTION_PATTERNS = {
			"(?i)(.*)(\\b)(select|insert|update|delete|drop|truncate|exec|union|create|alter|declare)(\\b)(.*)",
			"(?i)(.*)(\\b)(and|or|not|like|between|in|grant|revoke)(\\b)(.*)",
			"(?i)(.*)(\\b)(xp_cmdshell|xp_regread|xp_regwrite)(\\b)(.*)",
			"(?i)(.*)(--[\\s]*|#|/\\*|\\*/|;|@@|@)(.*)",
			"(?i)(.*)(\\b)(sysobjects|syscolumns|sysusers)(\\b)(.*)",
			"(?i)(.*)(\\b)(information_schema|user_tables|all_tables)(\\b)(.*)" };
	
	private static final List<Pattern> patterns = Arrays.stream(SQL_INJECTION_PATTERNS).map(Pattern::compile).toList();

	
	// 检查给定的值是否存在 SQL 注入风险
	public boolean containsSqlInjection(String value) {
		if (value == null || value.isEmpty()) {
			log.debug("Value is null or empty, returning false for SQL injection check.");
			return false; // 如果值为空，返回 false
		}
		// 检查是否匹配任何 SQL 注入模式
		boolean isMatch = patterns.stream().anyMatch(pattern -> pattern.matcher(value).matches());
		if (isMatch) {
			log.warn("Potential SQL injection detected in value: {}", value);
		} else {
			log.debug("No SQL injection detected in value: {}", value);
		}
		return isMatch;
	}

}
